package com.fingard.dsp.bank.directbank.cmbunion01;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.directbank.cmbunion01.util.BoingPay;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;

public class CMBUnion01JSAPIOrder extends CMBUnifiedOrder implements IJSAPIOrder {

	@Override
	public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
		RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
		retAts.rdSeq = p_req.rdSeq;
		try {
			ActSetItem actItem = this.getBankConfig().getActSetItem(
					p_req.ownAct, "");
			if (actItem != null) {
				Map<String, Object> order = new HashMap<String, Object>();
				order.put("mch_app_id", p_req.ownAct);// 商户appId
				order.put("pay_interface_no", "3004");// 支付通道编号 3004004
				order.put("out_order_no", p_req.rdSeq);// 商户订单号
				if (StringHelper.hasAnyChar(p_req.description)) {
					//order.put("order_desc", p_req.description);
				}
				order.put("pay_amount", changeCurToFen(p_req.amount));// 支付金额
				if (StringHelper.hasAnyChar(p_req.openid)) {
					order.put("buyer_user_id", p_req.openid);// 用户ID
				}else{
					if (StringHelper.isNullOrEmpty(p_req.code)) {
						retAts.respCode = "-1";
						retAts.respInfo = "Code和Openid不能同时为空";
						
						return retAts;
					} else {
						if (StringHelper.isNullOrEmpty(actItem.appSecret)) {
							retAts.respCode = "-1";
							retAts.respInfo = "未配置公众号的appsecret";
							
							return retAts;
						} else {
							HashMap<String, String> hashOpenid = getOpenid(actItem.appId, actItem.appSecret, p_req.code);

							if (hashOpenid.get("RespCode").equals("0")) {
								if (hashOpenid.containsKey("openid")) {
									order.put("buyer_user_id", hashOpenid.get("openid"));
								} else {
									retAts.respCode = "-1";
									retAts.payInfoCode = FailCode.E9981;
									
									String errcode = "";
									if (hashOpenid.containsKey("errcode")) {
										errcode = hashOpenid.get("errcode");
									}
									
									String errmsg = "";
									if (hashOpenid.containsKey("errmsg")) {
										errmsg = hashOpenid.get("errmsg");
									}
									
									retAts.respInfo = StringHelper.joinNotEmpty("-", errcode, errmsg);
									retAts.transState = PaymentState.FAIL_Payment;
									
									return retAts;
								}
							} else {
								retAts.respCode = "-1";
								retAts.respInfo = hashOpenid.get("RespInfo");
								
								return retAts;
							}
						}
					}
				}
				
				String notify_url = actItem.notifyURL;
				if (StringHelper.hasAnyChar(notify_url)) {
					order.put("back_url", notify_url);//后台通知地
				}
				if (StringHelper.hasAnyChar(p_req.productId)) {
					order.put("order_name", p_req.productId);
				}
				boolean limit = getBankConfig().getValueAsBool("limitPay");
	            WriteBankUrlLogLn("招商聚合能否用信用卡支付："+limit);
	            if(!limit){
	            	order.put("limit_pay", "no_credit"); 
	            }
				order.put("pay_context", "JSAPI");
				order.put("terminal_id", "");
				order.put("user_ip", actItem.createIP);
				if (StringHelper.hasAnyChar(p_req.timeStart)) {
					order.put("start_time", Format.DateTimeFormat.format(Format.DateTime14Format.parse(p_req.timeStart)));
				}
				if (StringHelper.hasAnyChar(p_req.timeExpire)) {
					order.put("expire", Format.DateTimeFormat.format(Format.DateTime14Format.parse(p_req.timeExpire)));
				}
				order.put("remark", p_req.attach);
				order.put("mch_wx_app_id", actItem.userCode);//商户微信公众号
				JSONObject ext_user_info = new JSONObject();
				ext_user_info.put("name", p_req.oppActName);
				ext_user_info.put("mobile", p_req.cellPhone);
				String cert_type = getBankConfig().getMapValueByKey("certTypeMapping", p_req.certType);
				ext_user_info.put("cert_type", cert_type);
				ext_user_info.put("cert_no", p_req.certNumber);
				ext_user_info.put("min_age", "16");
				ext_user_info.put("fix_buyer", "T");
				ext_user_info.put("need_check_info", "T");
				order.put("ext_user_info", ext_user_info);
				// order.put("goods_detail", new JSONObject());
				// 
				// order.put("out_store_id", "");
				// order.put("out_terminal_id", "");
				// order.put("operator_id", "");
				// order.put("limit_pay", "");
				// order.put("undiscountable_amount", "0");
				// order.put("store_id", "");
				WriteBankUrlLogLn("招商聚合地址：" + bankFront.getUrl("unifiedPay"));
				WriteBankUrlLogLn("招商聚合请求参数：" + order);
				String[] RSApath = actItem.ownCertFilePath.split(",");
				setConfig(actItem.merchantId, bankFront.getUrl("unifiedPay"), RSApath[0],
						RSApath[1], actItem.ownKeyStorePath,
						actItem.oppCertFilePath, actItem.ownKeyPassword);

				JSONObject ret = BoingPay.getCashier().call(
						"cod.pay.order.native_pay", order);

				WriteBankLogStep3("招商聚合返回：" + ret);
				if(ret.getString("error_code") == null){
					retAts.respCode = "0";
					retAts.respInfo = "请求成功";
					retAts.customHashMap = new HashMap<String, String>();
					retAts.customHashMap.put("appId", ret.getString("mch_wx_app_id"));
					retAts.customHashMap.put("nonceStr", ret.getString("nonce_str"));
					retAts.customHashMap.put("timeStamp", ret.getString("timestamp"));
					retAts.customHashMap.put("package",	"prepay_id="+ret.getString("prepay_id"));
					retAts.customHashMap.put("signType", ret.getString("sign_type"));
					retAts.customHashMap.put("paySign",	ret.getString("pay_sign"));
					retAts.outTransID = ret.getString("order_no");
				}else{
					retAts.respCode = "-1";
					retAts.respInfo = ret.getString("error_code")+"+"+ret.getString("message");
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		return retAts;
	}

	@Override
	public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
		return queryUnifiedOrder(p_req);
	}

	@Override
	public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
		// TODO Auto-generated method stub
		return null;
	}

}
